<template>
  <div>
    <h1 style="text-align: center">人员增加</h1>

    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      status-icon
    >
      <!-- 基本信息 -->
      <div>
        <el-divider content-position="left">基本信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="姓名" prop="staffName">
              <el-input v-model="ruleForm.staffName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="ruleForm.gender">
                <el-radio :value="false">男</el-radio>
                <el-radio :value="true">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="员工编号" prop="employeeID">
              <el-input v-model="ruleForm.employeeID" placeholder="请输入" />
            </el-form-item>

            <el-form-item label="身份证号" prop="idNumber">
              <el-input v-model="ruleForm.idNumber" placeholder="请输入" />
            </el-form-item>

            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="ruleForm.phone" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="头像" prop="photograph">
              <el-upload
                class="avatar-uploader"
                action="http://10.31.56.6:8000/route/api/Staff/UploadFile"
                :show-file-list="true"
                :on-success="handleAvatarSuccess"
              >
                <img
                  v-if="ruleForm.photograph"
                  :src="
                    'http://10.31.56.6:8000/route/Pic/' + ruleForm.photograph
                  "
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 入职信息 -->
      <div>
        <el-divider content-position="left">入职信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="单位" prop="unitName">
              <el-input v-model="ruleForm.unitName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="员工状态" prop="staffStateId">
              <el-select v-model="ruleForm.staffStateId" placeholder="请选择">
                <el-option
                  v-for="item in staffState"
                  :key="item.staffStateId"
                  :label="item.staffStateName"
                  :value="item.staffStateId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="部门" prop="departmentId">
              <el-select v-model="ruleForm.departmentId" placeholder="请选择">
                <el-option
                  v-for="item in departmentInfo"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="入职日期" prop="entryDate" required>
              <el-date-picker
                v-model="ruleForm.entryDate"
                type="date"
                placeholder="请选择"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="职务" prop="postId">
              <el-select v-model="ruleForm.postId" placeholder="请选择">
                <el-option
                  v-for="item in postInfo"
                  :key="item.postId"
                  :label="item.postName"
                  :value="item.postId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="岗位" prop="stationId">
              <el-select v-model="ruleForm.stationId" placeholder="请选择">
                <el-option
                  v-for="item in station"
                  :key="item.stationId"
                  :label="item.stationName"
                  :value="item.stationId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 账号信息 -->
      <div>
        <el-divider content-position="left">账号信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="账号" prop="accountNumber">
              <el-input v-model="ruleForm.accountNumber" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="ruleForm.password"
                placeholder="请输入"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="角色" prop="roleId">
              <el-select v-model="ruleForm.roleId" placeholder="请选择">
                <el-option
                  v-for="item in role"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0"></el-col>
        </el-row>

        <!-- <el-form-item label="所在区域" prop="provinceId">
          <el-select
            v-model="ruleForm.provinceId"
            placeholder="请选择省份"
            style="width: 200px"
            @change="getCity(ruleForm.provinceId)"
          >
            <el-option
              v-for="item in province"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>

          <el-select
            v-model="ruleForm.cityId"
            placeholder="请选择城市"
            style="width: 200px"
          >
            <el-option
              v-for="item in city"
              :key="item.cityId"
              :label="item.cityName"
              :value="item.cityId"
            />
          </el-select>

          <el-select
            v-model="ruleForm.countyId"
            placeholder="请选择区/县"
            style="width: 200px"
          >
            <el-option
              v-for="item in county"
              :key="item.countyId"
              :label="item.countyName"
              :value="item.countyId"
            />
          </el-select>
        </el-form-item> -->

        <el-form-item label="所在区域" prop="area">
          <el-cascader
            v-model="selectedOptions"
            :options="options"
            @change="handleChange"
          />
        </el-form-item>

        <el-form-item label="详细地址" prop="location">
          <el-input type="textarea" v-model="ruleForm.location" />
        </el-form-item>
      </div>

      <el-form-item>
        <el-button type="primary" style="margin-left: 540px;" @click="submitForm(ruleFormRef)">
          保存
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import axios from "axios";
import { useRouter } from "vue-router";
import { reactive, ref, onMounted } from "vue";
import {
  ElMessage,
  type FormInstance,
  type FormRules,
  type UploadProps,
} from "element-plus";
import { regionData, codeToText } from "element-china-area-data";

const router = useRouter();

//员工状态
const staffState = ref();

//部门名称
const departmentInfo = ref();

//职务
const postInfo = ref();

//岗位
const station = ref();

//省份
const province = ref();

//城市
const city = ref();

//区/县
const county = ref();

//角色
const role = ref();

interface RuleForm {
  staffName: string;
  gender: boolean;
  employeeID: string;
  idNumber: string;
  phone: string;
  photograph: string;
  unitName: string;
  staffStateId: string;
  departmentId: string;
  entryDate: string;
  postId: string;
  stationId: string;
  accountNumber: string;
  password: string;
  roleId: string;
  // provinceId: number;
  // cityId: number;
  // countyId: number;
  area: string;
  location: string;
}

const ruleFormRef = ref<FormInstance>();
//员工添加表单
const ruleForm = reactive<RuleForm>({
  staffName: "",
  gender: false,
  employeeID: "",
  idNumber: "",
  phone: "",
  photograph: "",
  unitName: "",
  staffStateId: "",
  departmentId: "",
  entryDate: "",
  postId: "",
  stationId: "",
  accountNumber: "",
  password: "",
  roleId: "",
  // provinceId: "",
  // cityId: "",
  // countyId: "",
  area: "",
  location: "",
});

//验证
const rules = reactive<FormRules<RuleForm>>({
  staffName: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z]{0,15}$/,
      message: "只允许输入中文或字母，最多输入15位",
      trigger: "blur",
    },
  ],
  employeeID: [
    { required: true, message: "请输入员工编号", trigger: "blur" },
    {
      pattern: /^\d{4}\d{2}\d{2}\d{4}$/,
      message: "请以年月日开头，填写12位编号",
      trigger: "blur",
    },
  ],
  idNumber: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    {
      pattern:
        /^\d{6}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}([0-9Xx])$/,
      message: "身份证号格式不正确",
      trigger: "blur",
    },
  ],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[34578]\d{9}$/,
      message: "手机号格式不正确",
      trigger: "blur",
    },
  ],
  photograph: [
    {
      required: true,
      message: "请上传图片",
      trigger: "change",
    },
  ],
  unitName: [
    { required: true, message: "请输入单位", trigger: "blur" },
    {
      pattern: /^[\u4e00-\u9fa5]{0,15}$/,
      message: "只允许输入最多15位中文",
      trigger: "blur",
    },
  ],
  staffStateId: [
    { required: true, message: "请选择员工状态", trigger: "change" },
  ],
  departmentId: [{ required: true, message: "请选择部门", trigger: "change" }],
  entryDate: [
    {
      type: "date",
      required: true,
      message: "请选择入职日期",
      trigger: "change",
    },
  ],
  postId: [{ required: true, message: "请选择职务", trigger: "change" }],
  stationId: [{ required: true, message: "请选择岗位", trigger: "change" }],
  accountNumber: [
    { required: true, message: "请输入账号", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9]{4,16}$/,
      message: "支持字母与数字组合，长度4-16位",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9]{6,16}$/,
      message: "支持字母与数字组合，长度6-16位",
      trigger: "blur",
    },
  ],
  roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
  //provinceId: [{ required: true, message: "请选择城市", trigger: "change" }],
  area: [{ required: true, message: "请选择所在区域", trigger: "change" }],
  location: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
});

//获取员工状态
const getStaffState = () => {
  axios.get("Readroute/api/StaffState/GetStaffStates").then((res) => {
    if (res.data) {
      //console.log(res.data);
      staffState.value = res.data;
    }
  });
};

//获取部门
const getDepartment = () => {
  axios.get("Readroute/api/Department/GetDepartmentInfo").then((res) => {
    departmentInfo.value = res.data;
  });
};

//获取职务
const getPost = () => {
  axios.get("Readroute/api/PostInfo/GetAllPosts").then((res) => {
    postInfo.value = res.data;
  });
};

//获取岗位
const getStation = () => {
  axios.get("Readroute/api/Station/GetAllStations").then((res) => {
    station.value = res.data;
  });
};

//获取角色
const getRole = () => {
  axios.get("Readroute/api/RoleInfo/GetAllRole").then((res) => {
    role.value = res.data;
  });
};

// //获取省份
// const getProvince = () => {
//   axios.get("Readroute/api/Province/GetAllProvince").then((res) => {
//     //console.log(res.data);
//     province.value = res.data;
//   });
// };

// //获取城市
// const getCity = (provinceId) => {
//   axios
//     .get("Readroute/api/City/GetCityInfo?provinceId=" + provinceId)
//     .then((res) => {
//       console.log(res.data);
//       city.value = res.data;
//     });
// };

//绑定省市区
const options = ref(regionData);
const selectedOptions = ref([]);
const handleChange = () => {
  if (
    selectedOptions.value[0] != null &&
    selectedOptions.value[1] != null &&
    selectedOptions.value[2] != null
  ) {
    const str =
      codeToText[selectedOptions.value[0]] +
      "/" +
      codeToText[selectedOptions.value[1]] +
      "/" +
      codeToText[selectedOptions.value[2]];

    ruleForm.area = str;
  }
};

//图片上传
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  console.log(response);
  console.log(uploadFile);
  ruleForm.photograph = URL.createObjectURL(response);
};

//保存
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      //console.log(ruleForm);
      axios.post("route/api/Staff/AddStaff", ruleForm).then((res) => {
        if (res.data == 0) {
          ElMessage.error("此用户编号已存在！");
        } else {
          ElMessage.success("保存成功！");
          router.push("/src/views/Jurisdiction/StaffShow.vue");
        }
      });
    } else {
      return;
    }
  });
};

//加载
onMounted(() => {
  getStaffState();
  getDepartment();
  getPost();
  getStation();
  getRole();
  //getProvince();
  handleChange();
});
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>